<template>
  <div>
    <h2>我的申请</h2>
    <div style="margin-bottom:12px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
      <div>当前用户: <strong>{{ currentUserId || '未设置' }}</strong></div>
      <a-select v-model:value="filters.kind" placeholder="类型" allowClear style="width:110px">
        <a-select-option value="leave">请假/加班</a-select-option>
        <a-select-option value="purchase">采购</a-select-option>
      </a-select>
      <a-select v-model:value="filters.status" placeholder="状态" allowClear style="width:110px">
        <a-select-option value="pending">待审批</a-select-option>
        <a-select-option value="approved">已批准</a-select-option>
        <a-select-option value="rejected">已拒绝</a-select-option>
      </a-select>
      <a-select v-model:value="filters.apply_type" placeholder="请假类型" allowClear style="width:110px">
        <a-select-option value="leave">请假</a-select-option>
        <a-select-option value="overtime">加班</a-select-option>
      </a-select>
      <a-button size="small" @click="reloadFirst" :disabled="!currentUserId">查询</a-button>
      <a-button size="small" @click="resetFilters">重置</a-button>
    </div>
    <a-table :dataSource="rows" :loading="loading" :pagination="pagination" @change="handleTableChange" rowKey="process_instance_id" size="small">
      <a-table-column title="ID" dataIndex="id" key="id" />
      <a-table-column title="类型" key="business_kind" :customRender="({record}:any)=> kindLabel(record.business_kind)" />
      <a-table-column title="状态" key="status" :customRender="renderStatus" />
      <a-table-column title="当前步骤" key="current_tasks" :customRender="renderCurrentTask" />
      <a-table-column title="流程实例" dataIndex="process_instance_id" key="process_instance_id" />
        <a-table-column title="操作" key="actions">
          <template #default="{ record }">
            <a-button size="small" type="link" @click="showDetail(record.id)">详情</a-button>
          </template>
        </a-table-column>
    </a-table>

    <a-modal v-model:visible="detailModalVisible" title="申请详情" :footer="null" width="600px">
      <div v-if="detailLoading" style="text-align:center;padding:32px;">
        <a-spin />
      </div>
      <div v-else-if="detail">
        <div><strong>申请ID:</strong> {{ detail.id }}</div>
        <div><strong>类型:</strong> {{ kindLabel(detail.business_kind) }}</div>
        <div><strong>状态:</strong> {{ renderStatus({ record: detail }) }}</div>
        <div><strong>流程实例:</strong> {{ detail.process_instance_id }}</div>
        <div style="margin-top:16px;"><strong>流程进度:</strong></div>
        <a-steps :current="currentStep" direction="vertical">
          <a-step
            v-for="(step, idx) in detail.steps"
            :key="idx"
            :title="step.name + (step.operator ? '（' + step.operator + '）' : '')"
            :description="step.status"
          />
        </a-steps>
      </div>
      <div v-else style="text-align:center;padding:32px;">未找到详情</div>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { currentUserId } from '../store/user';
import { listApplications } from '../services/applications';
import { getApplicationDetail } from '../services/applications';

interface Filters { kind?: string; status?: string; apply_type?: string; }
const filters = ref<Filters>({});

interface LeaveRow {
  id: number;
  apply_type: string;
  leave_type: string | null;
  start_date: string;
  end_date: string;
  leave_hours: number;
  status: string;
  process_instance_id: string;
  reason: string;
  completed: boolean;
  current_tasks: { task_id?: string; name?: string; assignee?: string }[];
  business?: any;
}
const rows = ref<LeaveRow[]>([]);
const loading = ref(false);
const pagination = ref({ current: 1, pageSize: 20, total: 0, showSizeChanger: true, showTotal: (t:number)=>`共 ${t} 条` });

const STATUS_LABELS: Record<string, string> = {
  pending: '待审批',
  approved: '已批准',
  rejected: '已拒绝',
  cancelled: '已撤回',
  completed: '已完成',
  processing: '审批中'
};

const detailModalVisible = ref(false);
const detailLoading = ref(false);
const detail = ref<any>(null);
const currentStep = ref(0);

async function load(page = pagination.value.current, pageSize = pagination.value.pageSize) {
  if (!currentUserId.value) return;
  loading.value = true;
  try {
    const payload = await listApplications({
      applicant_id: currentUserId.value,
      kind: filters.value.kind || undefined,
      status: filters.value.status || undefined,
      apply_type: filters.value.apply_type || undefined,
      page,
      page_size: pageSize
    });
    rows.value = payload.items.map(item => ({
      completed: item.completed,
      business_kind: item.business.business_kind,
      status: item.business.status,
      id: item.business.id,
      process_instance_id: item.process_instance_id,
      current_tasks: item.current_tasks || [],
      business: item.business
    })) as any;
    pagination.value.total = payload.total;
    pagination.value.current = payload.page;
    pagination.value.pageSize = payload.page_size;
  } finally { loading.value = false; }
}

function handleTableChange(pag:any) {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  load(pag.current, pag.pageSize);
}

function reloadFirst() {
  pagination.value.current = 1;
  load(1, pagination.value.pageSize);
}

function resetFilters() {
  filters.value = {};
  reloadFirst();
}

function renderHours({ record }: any) { return record.leave_hours ?? record.leave_days ?? (record.kind==='purchase'?'' : '-'); }
function renderStatus({ record }: any) {
  const raw = record.status ?? (record.business?.status);
  if (typeof raw === 'string') {
    const normalized = raw.trim().toLowerCase();
    if (STATUS_LABELS[normalized]) {
      return STATUS_LABELS[normalized];
    }
    return raw;
  }
  if (record.approved === true) return STATUS_LABELS.approved;
  if (record.approved === false) return STATUS_LABELS.rejected;
  return STATUS_LABELS.pending;
}

function renderCurrentTask({ record }: any) {
  if (record.completed) {
    return '已完成';
  }
  const tasks = Array.isArray(record.current_tasks) ? record.current_tasks : [];
  if (tasks.length) {
    return tasks
      .map((t: any) => {
        const name = t.name || t.task_id || '未命名任务';
        const assignee = t.assignee ? `（${t.assignee}）` : '';
        return `${name}${assignee}`;
      })
      .join('，');
  }
  return '未开始';
}
function renderApplyType({ record }: any) { if (record.kind !== 'leave') return ''; const m: Record<string, string> = { leave: '请假', overtime: '加班' }; return m[record.apply_type] || record.apply_type || '-'; }
function renderLeaveType({ record }: any) { return record.kind==='leave' && record.apply_type === 'leave' ? (record.leave_type || '-') : ''; }
function kindLabel(kind:string){ return kind==='leave' ? '请假/加班' : kind==='purchase' ? '采购' : kind; }


async function showDetail(id: number) {
  detailModalVisible.value = true;
  detailLoading.value = true;
  detail.value = null;
  currentStep.value = 0;
  try {
    const res = await getApplicationDetail(id);
    detail.value = res;
    // 假设res.steps是流程步骤数组，res.current_step为当前步骤索引
    currentStep.value = res.current_step ?? 0;
  } catch (e) {
    detail.value = null;
  } finally {
    detailLoading.value = false;
  }
}

reloadFirst();

</script>